"""
FileName：report_generator.py
Description：
Author：gaojiahui
Time：2025/8/26 14:26
Website：https://gitee.com/gao-jiahui
"""
import json
import time
from pathlib import Path

from core.logger import logger
from utils.notifier import notifier


def generate_test_report(test_results: dict, report_dir: str = "test-reports"):
    """生成测试报告"""
    # 确保报告目录存在
    report_path = Path(report_dir)
    report_path.mkdir(exist_ok=True)

    # 生成时间戳
    timestamp = time.strftime("%Y%m%d_%H%M%S")

    # 生成JSON报告
    json_report = report_path / f"test_report_{timestamp}.json"
    with open(json_report, 'w', encoding='utf-8') as f:
        json.dump(test_results, f, ensure_ascii=False, indent=2)

    # 生成HTML报告
    html_report = generate_html_report(test_results, report_path / f"test_report_{timestamp}.html")

    logger.info(f"测试报告已生成: {json_report}, {html_report}")

    # 发送通知
    if notifier.enabled:
        notifier.send_test_report(test_results)

    return json_report, html_report


def generate_html_report(test_results: dict, output_path: Path) -> Path:
    """生成HTML格式的测试报告"""
    total = test_results.get("total", 0)
    passed = test_results.get("passed", 0)
    failed = test_results.get("failed", 0)
    skipped = test_results.get("skipped", 0)
    duration = test_results.get("duration", 0)

    success_rate = (passed / total * 100) if total > 0 else 0

    html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; }}
        .summary {{ background-color: #f5f5f5; padding: 15px; border-radius: 5px; }}
        .passed {{ color: green; }}
        .failed {{ color: red; }}
        .skipped {{ color: orange; }}
        .test-case {{ margin: 5px 0; padding: 5px; border-left: 3px solid #ccc; }}
        .failed-case {{ border-left-color: red; background-color: #ffeeee; }}
    </style>
</head>
<body>
    <h1>自动化测试报告</h1>
    <div class="summary">
        <h2>测试概览</h2>
        <p>执行时间: {time.strftime("%Y-%m-%d %H:%M:%S")}</p>
        <p>持续时间: {duration:.2f} 秒</p>
        <p>总计用例: <strong>{total}</strong></p>
        <p>通过用例: <strong class="passed">{passed}</strong></p>
        <p>失败用例: <strong class="failed">{failed}</strong></p>
        <p>跳过用例: <strong class="skipped">{skipped}</strong></p>
        <p>通过率: <strong>{success_rate:.2f}%</strong></p>
    </div>
"""

    # 添加失败用例详情
    if failed > 0:
        html_content += """
        <div>
        <h2>失败用例详情</h2>
        """
        for case in test_results.get("failed_cases", []):
            html_content += f"""
<div class="test-case failed-case">
            <h3>{case.get('name', '未知用例')}</h3>
            <p><strong>位置:</strong> {case.get('nodeid', '未知')}</p>
            <p><strong>原因:</strong> {case.get('reason', '未知原因')}</p>
        </div>
"""

            html_content += """
            </body>
            </html>
            """
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(html_content)

    return output_path
